package com.itboye.eweilisten.main;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.eweilisten.R;
import com.itboye.eweilisten.app.MyApplication;
import com.itboye.eweilisten.fragment.HomeFragment;
import com.itboye.eweilisten.fragment.MeFragment;
import com.itboye.eweilisten.fragment.SchoolReportFragment;
import com.itboye.eweilisten.fragment.ThinErrorFragment;
import com.itboye.eweilisten.me.login.LoginActivity;
import com.itboye.eweilisten.util.loadingutil.MAlert;
import com.itboye.eweilisten.util.logincontroller.LoginController;
import com.itboye.eweilisten.util.logincontroller.LoginedState;
import com.itboye.eweilisten.util.logincontroller.UnLoginState;
import com.itboye.eweilisten.util.network.NetState;
import com.itboye.eweilisten.util.sputil.Const;
import com.itboye.eweilisten.util.sputil.SPUtils;

import java.lang.reflect.Field;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    private FragmentManager fragmentManager;
    View me_layout, index_layout, message_layout, store_layout;
    //首页四大碎片
    private HomeFragment homeFragment;
    private ThinErrorFragment thinErrorFragment;
    private SchoolReportFragment schoolReportFragment;
    private MeFragment meFragment;
    private long touchTime = 0;
    private long waitTime = 2000;
    public static boolean isShowing1=false;
    public static boolean isShowing2=false;
    public static MainActivity act;
    private TextView textView;

    String uid;

    public static MainActivity onSetFragment() {
        return act;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT > 18) {
            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        // 注册广播接收器Start
        NetState receiver = new NetState();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);
        receiver.onReceive(this, null);
        // 注册广播接收器End
        setContentView(R.layout.activity_main);
        uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");

        // 创建TextView
        textView = new TextView(this);
        LinearLayout.LayoutParams lParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, getStatusBarHeight());
        textView.setBackgroundColor(Color.parseColor("#3F9FE0"));
        textView.setLayoutParams(lParams);
        initView();
        act = this;
        fragmentManager = getSupportFragmentManager();
        // 第一次启动时选中第0个tab
        setTabSelection(0);


        //退出登录发送过来的广播
        IntentFilter filter1 = new IntentFilter(MeFragment.EXIT);
        registerReceiver(loginReceiver, filter1);
        //登录的广播
        IntentFilter filter2 = new IntentFilter(LoginActivity.LOGIN);
        registerReceiver(loginReceiver, filter2);

    }

    BroadcastReceiver loginReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            uid = (String) SPUtils.get(MyApplication.instance, null, Const.ID, "");
        }

        ;
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(loginReceiver);
    }

    // 通过反射机制获取手机状态栏高度
    public int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    private void initView() {
        message_layout = findViewById(R.id.message_layout);
        store_layout = findViewById(R.id.store_layout);
        index_layout = findViewById(R.id.index_layout);
        me_layout = findViewById(R.id.me_layout);
        message_layout.setOnClickListener(this);
        index_layout.setOnClickListener(this);
        store_layout.setOnClickListener(this);
        me_layout.setOnClickListener(this);

        /**
         * 登录状态
         */
        if ((Boolean) SPUtils.get(MyApplication.instance, null,
                Const.IS_LOGINED, false)) {
            LoginController.setLoginState(new LoginedState());
            Log.v("logined", "已经登录");
        } else {
            LoginController.setLoginState(new UnLoginState());
            Log.v("logined", "未登录");
        }
    }

    /**
     * 根据传入的index参数来设置选中的tab页。
     *
     * @param index 每个tab页对应的下标。0表示消息，1表示联系人，2表示动态，3表示设置。
     */
    @SuppressLint("ResourceAsColor")
    public void setTabSelection(int index) {
        // 每次选中之前先清楚掉上次的选中状态
        clearSelection();
        // 开启一个Fragment事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 先隐藏掉所有的Fragment，以防止有多个Fragment显示在界面上的情况
        hideFragments(transaction);
        switch (index) {
            case 0:
                isShowing1=false;
                isShowing2=false;
                // 当点击了首页tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.geren_selected);
                ((TextView) findViewById(R.id.index_text))
                        .setTextColor(getResources().getColor(R.color.blue));
                if (homeFragment == null) {
                    // 如果MessageFragment为空，则创建一个并添加到界面上
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.content, homeFragment);
                } else {
                    // 如果MessageFragment不为空，则直接将它显示出来
                    transaction.show(homeFragment);
                }
                break;
            case 1:
                    if (uid == null || uid.equals("")) {//uid为空的时候跳转到登陆
                        Intent intent = new Intent(this, LoginActivity.class);
                        startActivity(intent);
                        return;
                    }

                    // 当点击了消息tab时，改变控件的图片和文字颜色
                    ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.cuoti_selsete);
                    ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.blue));
                    if (thinErrorFragment == null) {
                        // 如果ContactsFragment为空，则创建一个并添加到界面上
                        thinErrorFragment = new ThinErrorFragment();
                        transaction.add(R.id.content, thinErrorFragment);
                    } else {
                        // 如果ContactsFragment不为空，则直接将它显示出来
                            transaction.show(thinErrorFragment);


                    }


                break;
            case 2:
                    isShowing1=false;
                    if (uid == null || uid.equals("")) {//uid为空的时候跳转到登陆
                        Intent intent = new Intent(this, LoginActivity.class);
                        startActivity(intent);
                        return;
                    }
                    // 当点击了我的tab时，改变控件的图片和文字颜色
                    ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.chengjidan_selsete);
                    ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.blue));

                    if (schoolReportFragment == null) {
                        // 如果SettingFragment为空，则创建一个并添加到界面上
                        schoolReportFragment = new SchoolReportFragment();
                        transaction.add(R.id.content, schoolReportFragment);
                    } else {
                        // 如果SettingFragment不为空，则直接将它显示出来
                        transaction.show(schoolReportFragment);
                    }


                break;
            case 3:
                isShowing1=false;
                isShowing2=false;
                // 当点击了服务tab时，改变控件的图片和文字颜色
                ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.wode_slesel);
                ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.blue));
                if (meFragment == null) {
                    // 如果NewsFragment为空，则创建一个并添加到界面上
                    meFragment = new MeFragment();
                    transaction.add(R.id.content, meFragment);
                } else {
                    // 如果NewsFragment不为空，则直接将它显示出来
                    transaction.show(meFragment);
                }

                break;

            default:

                break;
        }
        transaction.commit();
    }

    /**
     * 清除掉所有的选中状态。
     */
    private void clearSelection() {
        ((ImageView) findViewById(R.id.index_image)).setImageResource(R.drawable.geren);
        ((TextView) findViewById(R.id.index_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.store_image)).setImageResource(R.drawable.cuoti);
        ((TextView) findViewById(R.id.store_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.message_image)).setImageResource(R.drawable.chengjidan);
        ((TextView) findViewById(R.id.message_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));
        ((ImageView) findViewById(R.id.me_image)).setImageResource(R.drawable.wode);
        ((TextView) findViewById(R.id.me_text)).setTextColor(getResources().getColor(R.color.home_bottom_gray));

    }

    /**
     * 将所有的Fragment都置为隐藏状态。
     *
     * @param transaction 用于对Fragment执行操作的事务
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (thinErrorFragment != null) {
            transaction.hide(thinErrorFragment);
        }
        if (schoolReportFragment != null) {
            transaction.hide(schoolReportFragment);
        }
        if (meFragment != null) {
            transaction.hide(meFragment);
        }

    }

    @Override
    public void onClick(View view) {
        String colorValue = "#FFFFFF";
        switch (view.getId()) {
            case R.id.me_layout:
                // 当点击了消息tab时，选中第1个tab
                setTabSelection(3);
                break;
            case R.id.index_layout:
                setTabSelection(0);
                break;
            case R.id.message_layout:
                setTabSelection(2);
                break;
            case R.id.store_layout:
                setTabSelection(1);

                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                MAlert.alert("再按一次退出", Gravity.TOP);
                touchTime = currentTime;
            } else {
                finish();
                //退出后关闭进程
                //   android.os.Process.killProcess(android.os.Process.myPid());
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {// 根据反馈值判断当前网络状态
            case 1:
                String keyStr = data.getStringExtra("key");
                System.out.println("--------- onActivityResult -------keyStr="
                        + keyStr);
                if ("-1".equals(keyStr)) {
                    MAlert.alert("网络不可用");
//                    showTips(R.drawable.tips_error, "网络不可用...");
//                    text_type.setText("当前网络不可用");
                } else {
                    MAlert.alert("网络恢复正常");
                    sendBroadcast(new Intent("connect_recover").putExtra("recover",400));
//                    showTips(R.drawable.tips_smile, "网络已恢复正常...");
                    if ("1".equals(keyStr)) {
//                        text_type.setText("当前连接网络为WiFi");
                    } else if ("2".equals(keyStr)) {
//                        text_type.setText("当前连接网络为wap网络");
                    } else if ("3".equals(keyStr)) {
//                        text_type.setText("当前连接网络为net网络");
                    }

                }

                break;
        }
    }


}
